package com.sunnada.edu.business.worker.service;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.sunnada.edu.business.project.service.ProjectMethods;
import com.sunnada.edu.business.worker.dao.WorkerDao;
import com.sunnada.edu.system.pub.common.CommonException;
import com.sunnada.edu.system.pub.common.Constants;
import com.sunnada.edu.system.pub.common.EXCELObject;
import com.sunnada.edu.system.pub.common.MD5;
import com.sunnada.edu.system.pub.common.RandomTool;
import com.sunnada.edu.system.pub.util.DateUtil;
import com.sunnada.edu.system.pub.util.Utils;

@Service
@Transactional
public class WorkerServiceImpl implements WorkerService {
	private static final Logger logger = LoggerFactory
			.getLogger(WorkerServiceImpl.class);
	@Resource
	WorkerDao workerDao;

	@Override
	public int getWorkerCots(HashMap<String, String> params) {
		return workerDao.getWorkerCots(params);
	}

	@Override
	public List<?> findWorkers(HashMap<String, String> params) {
		return workerDao.findWorkers(params);
	}

	@Override
	public int getWorkerProjectCots(HashMap<String, String> params) {
		return workerDao.getWorkerProjectCots(params);
	}

	@Override
	public List<?> findWorkerProjects(HashMap<String, String> params) {
		return workerDao.findWorkerProjects(params);
	}
	
	@Override
	public int getWorkerJcqkCots(HashMap<String, String> params) {
		return workerDao.getWorkerJcqkCots(params);
	}
	
	@Override
	public List<?> findWorkerJcqks(HashMap<String, String> params) {
		return workerDao.findWorkerJcqks(params);
	}

	@Override
	public String workerDelete(HashMap<String, String> params) {
		String msg = "";
		int num = workerDao.workerDelete(params);
		//如果是班组的班长，则放空
		WorkerMethods.delGroupMonitor(params);
		if (num == 0) {
			msg = "删除失败!";
		}else{
			String jobnos=params.get("jobnos");
			String []jobnoArray=jobnos.split(",");
			for(int i=0;i<jobnoArray.length;i++){
				//向外部发起新增工人的请求
				int result=WorkerMethods.sendDelWorkInfo(jobnoArray[i]);
				/*if(result==0){
					throw new RuntimeException("-----------------》删除工人接口调用失败");
				}*/
			}	
		}
		return msg;
	}

	@Override
	public String workerAdd(HttpServletRequest request,
			HashMap<String, String> params) {
		String msg = "";
		int Jcot = WorkerMethods.getWorkerCotByJobNo(params);
		int Tcot = WorkerMethods.getWorkerCotByTel(params);
		//判断工种是否自定义
		WorkerMethods.setWorkerType(params);
		if(Tcot>0){
			msg = "3";// 手机号已存在，请更换！
		}else if (Jcot > 0) {
			msg = "2";// 工号已存在，请更换！
		} else {
			String tel = params.get("tel");
			String pwd = tel.substring(tel.length() - 6, tel.length());
			String password = MD5.md5(tel + pwd);
			params.put("password", password);// 默认密码手机号末尾6位
			String recId = UUID.randomUUID().toString();
			params.put("recId", recId);
			int num = workerDao.workerAdd(params);

			if (num == 0) {
				msg = "0";// 失败
			} else {
				msg = "1";// 成功
				workerDao.workerSalaryAdd(params);// 薪酬配置

				// 合同添加
				CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
						request.getSession().getServletContext());
				if (multipartResolver.isMultipart(request)) {
					MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
					List<MultipartFile> filelist = multiRequest
							.getFiles("contract");
					for (int i = 0; i < filelist.size(); i++) {
						MultipartFile file = filelist.get(i);
						String fileName = file.getOriginalFilename();// 原文件名
						String fileType = file.getContentType();// 原文件类型
						String name = file.getName();// form表单字段name属性值
						// 存文件
						String savePath = FileSave(file, request);
						params.put("path", savePath);
						params.put("fileName", fileName);
						params.put("owner", recId);
						WorkerMethods.contractAdd(params);// 新增合同
					}
				}
				//是否向外部发起新增工人的请求
				String  machineSave=params.get("machineSave");
				if("1".equals(machineSave)){
					String ctp=request.getSession().getServletContext().getRealPath("/");
					params.put("ctp", ctp);
					int result=WorkerMethods.sendAddWorkInfo(params);
					if(result==0){
						msg="4";
						throw new RuntimeException("-----------------新增工人接口调用失败---------------------");
					}
				}
			}
		}

		return msg;
	}

	@SuppressWarnings("unchecked")
	@Override
	public String workerUpdate(HttpServletRequest request,
			HashMap<String, String> params) {
		String msg = "";
		int cot = WorkerMethods.getWorkerCotByJobNo(params);
		int Tcot = WorkerMethods.getWorkerCotByTel(params);
		//如果手机发生变化，重置工人登录密码
		if(Tcot==0){
			String tel = params.get("tel");
			String pwd = tel.substring(tel.length() - 6, tel.length());
			String password = MD5.md5(tel + pwd);
			params.put("password", password);// 默认密码手机号末尾6位
		}
		
		if(Tcot>1){
			msg = "3";// 手机号已存在，请更换！
		}else if (cot > 1) {
			msg = "2";// 工号已存在，请更换！
		} else {
			
			int num = workerDao.workerUpdate(params);
			WorkerMethods.updateMontor(params);//如果工人是班长，则修改班长班长信息
			if (num == 0) {
				msg = "0";// 失败
			} else {
				msg = "1";// 成功
				workerDao.workerSalaryUpdate(params);
				// 创建一个通用的多部分解析器
				CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
						request.getSession().getServletContext());
				// 判断 request 是否有文件上传,即多部分请求
				if (multipartResolver.isMultipart(request)) {
					// 转换成多部分request
					MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
					// 取得request中的所有文件名
					List<MultipartFile> filelist = multiRequest
							.getFiles("contract");// 图片列表
					for (int i = 0; i < filelist.size(); i++) {
						MultipartFile file = filelist.get(i);
						String fileName = file.getOriginalFilename();// 原文件名
						String fileType = file.getContentType();// 原文件类型
						String name = file.getName();// form表单字段name属性值
						// 存文件
						String savePath = FileSave(file, request);
						params.put("path", savePath);
						params.put("fileName", fileName);
						params.put("owner", params.get("recId"));
						WorkerMethods.contractAdd(params);// 新增合同
					}
				}
				
				//是否向外部发起新增工人的请求
				String  machineSave=params.get("machineSave");
				if("1".equals(machineSave)){
					String ctp=request.getSession().getServletContext().getRealPath("/");
					params.put("ctp", ctp);
					int result=WorkerMethods.sendUpdateWorkInfo(params);
					if(result==0){
						msg="4";
						throw new RuntimeException("-----------------》修改工人接口调用失败");
					}
				}
			}
		}
		return msg;
	}

	@Override
	public Map getWorkerByRecId(HashMap<String, String> params) {
		return workerDao.getWorkerByRecId(params);
	}

	@Override
	public Map<String, String> getWorker(HashMap<String, String> params) {
		return workerDao.getWorker(params);
	}

	@Override
	public String workerPwdReset(HashMap<String, String> params) {
		String WorkerIds = params.get("recIds");
		if (WorkerIds != null) {
			String s[] = WorkerIds.split(",");
			for (int i = 0; i < s.length; i++) {
				HashMap<String, String> param = new HashMap<String, String>();
				param.put("WorkerId", s[i]);
				String phone = s[i];
				String pwd = phone.substring(phone.length() - 6, phone.length());
				/*String randpw = RandomTool.randNum(3) + "@"
						+ RandomTool.randLetter(4);
				System.out.println("重置密码的账号:" + s[i] + "重置后的密码：" + randpw);*/
				String passWord = MD5.md5(s[i] + pwd);
				param.put("passWord", passWord);
				workerDao.workerPwdReset(param);
				logger.info("重置密码的账号:" + s[i] + "重置后的密码：" + pwd);

			}
		}
		return "密码重置成功！重置后的密码为手机号末尾六位";
	}

	@Override
	public String workerEnable(HashMap<String, String> params) {
		String msg = "";
		int num = workerDao.workerEnable(params);
		if (num == 0) {
			msg = "启用失败！";
		}
		return msg;
	}

	@Override
	public String workerDisable(HashMap<String, String> params) {
		String msg = "";
		int num = workerDao.workerDisable(params);
		if (num == 0) {
			msg = "停用失败！";
		}
		return msg;
	}

	@Override
	public void exportWorker(HashMap<String, String> params,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		List dataList = workerDao.exportWorker(params);
		String realPath = request.getSession().getServletContext()
				.getRealPath("/file/temp");
		EXCELObject s = new EXCELObject();
		s.seteFilePath(realPath);
		String[] titH = { "姓名", "年龄", "性别", "籍贯", "工种",  "班组",  "在册工龄", "手机号", "合同状态" };
		String[] titN = { "NAME", "AGE", "SEX" ,"NATIVE","WORKTYPE","GROUPNAME","REGISTEREDAGE","TEL","CONTRACTSTATE"};
		s.setFname("工人数据 "); // 临时文件名
		s.setTitle("工人数据"); // 大标题名称
		s.setTitH(titH);
		s.setTitN(titN);
		s.setDataList(dataList);
		File exportFile = null;
		exportFile = s.setData();
		String excelName = "工人数据" + DateUtil.getCurrentTime() + ".xls";
		s.exportExcel("工人数据", excelName, exportFile, request, response);

	}

	public static final String getValueFromCell(Cell cell) {
		if (cell == null) {
			return "";
		}
		cell.setCellType(Cell.CELL_TYPE_STRING);
		String value = null;
		switch (cell.getCellType()) {
		case Cell.CELL_TYPE_NUMERIC: // 数字
			value = String.valueOf(cell.getNumericCellValue());
			break;
		case Cell.CELL_TYPE_STRING: // 字符串
			value = cell.getStringCellValue();
			break;
		case Cell.CELL_TYPE_FORMULA: // 公式
			// 用数字方式获取公式结果，根据值判断是否为日期类型
			double numericValue = cell.getNumericCellValue();
			value = String.valueOf(numericValue);
			break;
		case Cell.CELL_TYPE_BLANK: // 空白
			value = StringUtils.EMPTY;
			break;
		case Cell.CELL_TYPE_BOOLEAN: // Boolean
			value = String.valueOf(cell.getBooleanCellValue());
			break;
		case Cell.CELL_TYPE_ERROR: // Error，返回错误码
			value = String.valueOf(cell.getErrorCellValue());
			break;
		default:
			value = StringUtils.EMPTY;
			break;
		}
		return value;
	}

	public String FileSave(MultipartFile file, HttpServletRequest request) {
		if (Utils.isNull(file)) {
			return "";
		}
		// 实际名称
		String fileName = file.getOriginalFilename();
		// 保存附件
		if (Utils.isNotNull(fileName)) {
			// 物理根目录
			String rootPath = request.getSession().getServletContext()
					.getRealPath("/");
			// 相对路径
			String filePath = "upload/worker/"
					+ DateUtil.simpleDateFormat("yyyyMM").format(new Date());
			// 保存文件路径
			String savePath = filePath
					+ "/"
					+ DateUtil.simpleDateFormat("yyyyMMddHHmmssSSS").format(
							new Date())
					+ fileName.substring(fileName.lastIndexOf("."),
							fileName.length());

			if (!new File(rootPath + filePath).exists()) {
				new File(rootPath + filePath).mkdirs();
			}

			try {
				file.transferTo(new File(rootPath + savePath));
				return savePath;
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		}
		return "";
	}
	
	@Override
	public int selectWorkerCots(HashMap<String, String> params) {
		return workerDao.selectWorkerCots(params);
	}

	@Override
	public List<?> selectWorkers(HashMap<String, String> params) {
		return workerDao.selectWorkers(params);
	}

	@Override
	public List<?> getWorkerList(HashMap<String, String> params) {
		return workerDao.getWorkerList(params);
	}

}
